﻿using System;
using System.Linq;
using System.ServiceModel;
using System.Threading;
using MBWebService.Core.Classes;
using MBWebService.Server.Proxy;
using Microsoft.MediaCenter.Hosting;
using Microsoft.MediaCenter;

namespace MBWebService.Core.Client
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class MediaBrowserClient : IMediaBrowserServerCallback
    {
        #region Private Members

        WebServicePlaybackController _controller;

        #endregion

        WebServicePlaybackController Controller
        {
            get
            {
                if (_controller == null)
                {
                    _controller = new WebServicePlaybackController();
                }

                return _controller;
            }   
        }

        #region IMediaBrowserServerCallback Members

        public bool PlayItem(string[] collection, bool queue)
        {
            bool retVal = false;
            if (collection.Any())
            {
                int count = collection.Count();
                var collectionItem = collection.First();
                var type = ResolveFileToType(collectionItem);
                if (count == 1)
                {
                    if (!(type == MediaType.Video && queue))
                    {
                        retVal = AddInHost.Current.MediaCenterEnvironment.PlayMedia(type, collectionItem, queue);
                    }
                    else
                    {
                        LogMessage("ERROR: Cannot queue a video file.");
                    }
                }
                else
                {
                    if (type == MediaType.Audio && queue)
                    {
                        foreach (var bob in collection)
                        {
                            retVal = retVal || AddInHost.Current.MediaCenterEnvironment.PlayMedia(MediaType.Audio, bob, true);
                        }
                    }
                    else
                    {
                        // Create the wpl and play it.
                        string path = MediaBrowser.Library.PlayableItem.CreateWPLPlaylist(Guid.NewGuid().ToString(), collection);
                        retVal = AddInHost.Current.MediaCenterEnvironment.PlayMedia(type, collectionItem, queue);
                    }
                }
            }

            if (retVal && !AddInHost.Current.MediaCenterEnvironment.MediaExperience.IsFullScreen)
            {
                Thread.Sleep(200);
                AddInHost.Current.MediaCenterEnvironment.MediaExperience.GoToFullScreen();
            }

            return retVal;
        }

        public MBWebService.Server.Proxy.NowPlayingItem GetNowPlaying(bool waitForUpdate)
        {
            var bob = Controller.GetNowPlaying(waitForUpdate);
            MBWebService.Server.Proxy.NowPlayingItem item = new MBWebService.Server.Proxy.NowPlayingItem
            {
                DateCreated = bob.DateCreated,
                Elapsed = bob.Elapsed,
                Id = bob.Id,
                Name = bob.Name,
                State = (MBWebService.Server.Proxy.PlayState)bob.State,
                Title = bob.Title,
                TotalTime = bob.TotalTime,
                Type = (MBWebService.Server.Proxy.MediaTypes)bob.Type
            };
            return item;
        }

        public void SendCommand(CommandTypes command)
        {
            try
            {
                LogMessage("Received command '{0}'", command.ToString());
                switch (command)
                {
                    case CommandTypes.VolDown:
                        {
                            AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeDown();
                            break;
                        }
                    case CommandTypes.VolUp:
                        {
                            AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeUp();
                            break;
                        }
                    default:
                        {
                            MBWebService.Core.Classes.SendKeyCommander.SendCommand((MBWebService.Core.Enums.CommandTypes)command);
                            break;
                        }
                }
            }
            catch (Exception ex)
            {
                MBWebService.Core.Logging.Logger.Instance.LogMessage("Error sending command {0}; ERROR: {1}", command, ex.Message);
            }
        }

        public void Seek(int seconds)
        {
            MBWebService.Core.Logging.Logger.Instance.LogMessage("Seeking to {0}", seconds);
            try
            {
                TimeSpan time = TimeSpan.FromSeconds(seconds);
                Controller.Seek(time.Ticks);
            }
            catch (Exception ex)
            {
                MBWebService.Core.Logging.Logger.Instance.LogMessage("Error seeking to time {0}; ERROR: {1}", seconds, ex.Message);
            }
        }

        public void GoToScreen(ScreenType screenType, string extraInfo)
        {
            try
            {
                AddInHost.Current.MediaCenterEnvironment.NavigateToPage((PageId)((int)screenType), extraInfo);
            }
            catch (Exception ex)
            {
                MBWebService.Core.Logging.Logger.Instance.LogMessage("Error navigating to screen{0}; ERROR: {1}", screenType, ex.Message);
            }
        }

        #endregion

        private MediaCollectionItem GetCollectionItemFromFile(string fileName)
        {
            if (fileName.EndsWith(".lnk"))
            {
                fileName = MediaBrowser.Interop.ShortcutNativeMethods.ResolveShortcut(fileName);
            }

            return new MediaCollectionItem { Media = fileName };
        }

        private Microsoft.MediaCenter.MediaType ResolveFileToType(string item)
        {
            if (item.EndsWith("mp3"))
                return Microsoft.MediaCenter.MediaType.Audio;
            else
                return Microsoft.MediaCenter.MediaType.Video;
        }

        private void LogMessage(string message, params object[] stringFormatArgs)
        {
            MBWebService.Core.Logging.Logger.Instance.LogMessage(message, stringFormatArgs);
        }
    }
}
